package com.sinoglobal.wallet.activity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;

import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.app.SinoConstans;
import com.umeng.socialize.bean.CallbackConfig.ICallbackListener;
import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

/**
 * 
 * @author lgy
 * @createdate 2015-1-29 下午3:41:25
 * @Description:TODO (用一句话描述该类做什么) 有分享界面需要继承的基类 需要关联
 *                   social_sdk_library_project这个library
 */
public abstract class W_ShareAbstractActivity extends W_SinoBaseActivity {
	
	private static final String TAG = W_ShareAbstractActivity.class.getSimpleName();
	// 首先在您的Activity中添加如下成员变量
	protected final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share", RequestType.SOCIAL);
	private ICallbackListener listener;
	private UMImage umImage;
	private QQShareContent qqShareContent;
	private QZoneShareContent qZoneShareContent;
	private WeiXinShareContent weixinContent;
	private CircleShareContent circleMedia;
	private SinaShareContent sinaShareContent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// LogFile.logWrite(TAG + "-onCreate");
		shareInfo();
	}

	/**
	 * 
	 * @Description: 扫一扫用分享
	 * @param title
	 *            分享标题(目前添加的5个平台中 QQ好友 空间 微信 朋友圈需要)
	 * @param content
	 *            所有平台都需要
	 * @param url
	 *            分享url用于平台点击信息跳转(目前添加的5个平台中 QQ好友 空间 微信 朋友圈需要)
	 * @param pic
	 *            分享图片url 可以根据传入内容进行判断是否使用
	 * 
	 */
	public void setQRShare(String title, String content, String url, String pic) {
		// LogFile.logWrite(TAG + "-setQRShare");
		mController.registerListener(listener);
		mController.openShare(W_ShareAbstractActivity.this, false);
		// 是否只有已登录用户才能打开分享选择页
		// 分享内容为空时，用默认的分享内容，不为空时用content作为分享内容
		if (TextUtils.isEmpty(content)) {
			content = getResources().getString(R.string.share);
		} else if (content.length() > 50) {
			content = content.substring(0, 50) + "...";
		}
		if (TextUtils.isEmpty(url)) {
			url = getResources().getString(R.string.sharePath);
		}
		if (TextUtils.isEmpty(title)) {
			title = getResources().getString(R.string.w_shareTitle);
		}
		if (TextUtils.isEmpty(pic)) {
			umImage = new UMImage(W_ShareAbstractActivity.this, R.drawable.ic_launcher);
		} else if ("isTwoCode".equals(pic)) {
			umImage = new UMImage(W_ShareAbstractActivity.this, R.drawable.me_set_yard);
		} else {
			umImage = new UMImage(W_ShareAbstractActivity.this, pic);
		}

		// 文本内容是 内容拼接url 最后拼接空格是因为 @好友时, @符号容易和前面的url冲突,导致url和@好友都不起作用
		// 这里是给sina用的
		mController.setShareContent(content + url + SinoConstans.BLANK);
		mController.setShareImage(umImage);

		qZoneShareContent.setTitle(title);
		qZoneShareContent.setTargetUrl(url);
		qZoneShareContent.setShareContent(content);
		qZoneShareContent.setShareImage(umImage);
		mController.setShareMedia(qZoneShareContent);

		qqShareContent.setTitle(title);
		qqShareContent.setTargetUrl(url);
		qqShareContent.setShareContent(content);
		qqShareContent.setShareImage(umImage);
		mController.setShareMedia(qqShareContent);

		circleMedia.setTitle(title);
		circleMedia.setTargetUrl(url);
		circleMedia.setShareContent(content);
		circleMedia.setShareImage(umImage);
		mController.setShareMedia(circleMedia);

		weixinContent.setTitle(title);
		weixinContent.setTargetUrl(url);
		weixinContent.setShareContent(content);
		weixinContent.setShareImage(umImage);
		mController.setShareMedia(weixinContent);

	}

	/**
	 * 
	 * @author lgy
	 * @createdate 2015-1-29 下午3:23:10
	 * @Description: (用一句话描述该方法做什么) 分享面板打开和设置内容
	 * @param inviteContent
	 *            分享内容
	 * @param platform
	 *            分享平台 如果传null 使用友盟默认分享面板
	 * @param shareUrl
	 *            分享链接
	 * @param isIcon
	 *            Constants.SHARE_ICON 分享logo Constants.SHARE_TWO_CODE分享二维码
	 *            网络图片直接传入链接
	 * 
	 */
	public void setShare(final String content, final SHARE_MEDIA platform, final String shareUrl, String isIcon) {
		// LogFile.logWrite(TAG + "-setShare");
		String shareContent = ""; // 固定分享内容
		String sharePath = ""; // 固定分享地址
		if (!TextUtils.isEmpty(content)) {
			shareContent = content;
		}
		if (!TextUtils.isEmpty(shareUrl)) {
			sharePath = shareUrl;
		}

		if (SinoConstans.SHARE_ICON.equals(isIcon) || TextUtils.isEmpty(isIcon)) {
			// TODO 分享icon 记得换图片
			umImage = new UMImage(W_ShareAbstractActivity.this, R.drawable.ic_launcher);
		} else if (SinoConstans.SHARE_QR_CODE.equals(isIcon)) {
			// TODO 分享二维码 记得换图片
			umImage = new UMImage(W_ShareAbstractActivity.this, R.drawable.me_set_yead1);
		} else {
			// TODO 分享网络图片 直接传入图片地址就可以
			umImage = new UMImage(W_ShareAbstractActivity.this, isIcon);
		}
		// 设置分享内容
		mController.setShareContent(content + shareUrl + SinoConstans.BLANK);
		mController.setShareImage(umImage);

		// 支持QQ空间
		qZoneShareContent.setTitle(getResources().getString(R.string.w_shareTitle));
		qZoneShareContent.setShareContent(shareContent);
		qZoneShareContent.setShareImage(umImage);
		qZoneShareContent.setTargetUrl(sharePath);
		mController.setShareMedia(qZoneShareContent);
		// QQ好友
		qqShareContent.setTitle(getResources().getString(R.string.w_shareTitle));
		qqShareContent.setShareContent(shareContent);
		qqShareContent.setShareImage(umImage);
		qqShareContent.setTargetUrl(sharePath);
		mController.setShareMedia(qqShareContent);

		// 设置微信好友内容
		weixinContent.setTitle(getResources().getString(R.string.w_shareTitle));
		weixinContent.setShareContent(shareContent);
		weixinContent.setShareImage(umImage);
		weixinContent.setTargetUrl(sharePath);
		mController.setShareMedia(weixinContent);
		// 设置微信朋友圈内容
		circleMedia.setShareContent(getResources().getString(R.string.w_shareTitle));
		circleMedia.setTitle(shareContent);
		circleMedia.setShareImage(umImage);
		circleMedia.setTargetUrl(sharePath);
		mController.setShareMedia(circleMedia);
		// 设置微博分享内容
		sinaShareContent.setShareContent(shareContent + sharePath);
		sinaShareContent.setShareImage(umImage);
		mController.setShareMedia(sinaShareContent);
		// 如果不是单个分享平台 使用友盟默认分享平台
		if (platform == null) {
			mController.registerListener(listener);
			try {
				mController.openShare(W_ShareAbstractActivity.this, false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 参数1为当前Activity对象， 参数2为要分享到的目标平台， 参数3为分享操作回调接口
			mController.postShare(W_ShareAbstractActivity.this, platform, new SnsPostListener() {

				@Override
				public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
					String msg = "setShare postShare:shareMedia=" + arg0 + ",arg1=" + arg1 + ",entity=" + arg2.getNickName() + ",extra=" + arg2.getExtra("access_token") + "," + arg2;
					// LogFile.logWrite(msg);
					if (arg1 == StatusCode.ST_CODE_SUCCESSED) {
						showToast(getResources().getString(R.string.share_ok));
					} else if (arg1 == 40000) {
					} else {
						showToast(getResources().getString(R.string.share_fail));
					}
				}

				@Override
				public void onStart() {
					showToast(getResources().getString(R.string.shareing));
				}

			});
		}
	}


	void getBitmapFromUrl(String path) {
		try {
			URL url = new URL(path);
			InputStream is = url.openStream();
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			Bitmap bm = BitmapFactory.decodeStream(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setWalletShare(String content, SHARE_MEDIA platform, String shareUrl, Bitmap isIcon) {
		// LogFile.logWrite(TAG + "-2setShare");
		String shareContent = ""; // 固定分享内容
		String sharePath = ""; // 固定分享地址
		if (!TextUtils.isEmpty(content)) {
			shareContent = content;
		}
		if (!TextUtils.isEmpty(shareUrl)) {
			sharePath = shareUrl;
		}
		umImage = new UMImage(W_ShareAbstractActivity.this, isIcon);
		// 设置分享内容
		mController.setShareContent(shareContent);
		mController.setShareImage(umImage);
		// 支持QQ空间
		qZoneShareContent.setTitle(getResources().getString(R.string.w_shareTitle));
		qZoneShareContent.setShareContent(shareContent);
		qZoneShareContent.setShareImage(umImage);
		qZoneShareContent.setTargetUrl(sharePath);
		mController.setShareMedia(qZoneShareContent);
		// QQ好友
		qqShareContent.setTitle(getResources().getString(R.string.w_shareTitle));
		qqShareContent.setShareContent(shareContent);
		qqShareContent.setShareImage(umImage);
		qqShareContent.setTargetUrl(sharePath);
		mController.setShareMedia(qqShareContent);
		// 设置微信好友内容
		weixinContent.setTitle(getResources().getString(R.string.w_shareTitle));
		weixinContent.setShareContent(shareContent);
		weixinContent.setShareImage(umImage);
		weixinContent.setTargetUrl(sharePath);
		mController.setShareMedia(weixinContent);
		// 设置微信朋友圈内容
		circleMedia.setShareContent(getResources().getString(R.string.w_shareTitle));
		circleMedia.setTitle(shareContent);
		circleMedia.setShareImage(umImage);
		circleMedia.setTargetUrl(sharePath);
		mController.setShareMedia(circleMedia);
		// 设置微博分享内容
		sinaShareContent.setShareContent(shareContent + sharePath);
		sinaShareContent.setTitle(getResources().getString(R.string.w_shareTitle));
		sinaShareContent.setShareImage(umImage);
		sinaShareContent.setTargetUrl(sharePath);
		mController.setShareMedia(sinaShareContent);

		// 如果不是单个分享平台 使用友盟默认分享平台
		if (platform == null) {
			mController.registerListener(listener);
			try {
				mController.openShare(W_ShareAbstractActivity.this, false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 参数1为当前Activity对象， 参数2为要分享到的目标平台， 参数3为分享操作回调接口
			mController.postShare(W_ShareAbstractActivity.this, platform, new SnsPostListener() {

				@Override
				public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
					String msg = "postShare:shareMedia=" + arg0 + ",arg1=" + arg1 + ",entity=" + arg2.getNickName() + ",extra=" + arg2.getExtra("access_token") + "," + arg2;
					// LogFile.logWrite(msg);
					if (arg1 == StatusCode.ST_CODE_SUCCESSED) {
						showToast(getResources().getString(R.string.share_ok));
					} else if (arg1 == 40000) {
					} else {
						showToast(getResources().getString(R.string.share_fail));
					}
				}

				@Override
				public void onStart() {
					showToast(getResources().getString(R.string.shareing));
				}

			});
		}
	}

	private void shareInfo() {
		// LogFile.logWrite(TAG + "-shareInfo");
		mController.getConfig().closeToast();
		mController.getConfig().setSsoHandler(new SinaSsoHandler()); // 如果新浪安装客户端,会走新浪客户端
		// 选择平台
		mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN, SHARE_MEDIA.SMS, SHARE_MEDIA.TENCENT);
		// 设置分享平台面板中显示的平台
		mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE);
		// getAccessToken();// add 2015.09.28
		weixinContent = new WeiXinShareContent();
		circleMedia = new CircleShareContent();
		qZoneShareContent = new QZoneShareContent();
		qqShareContent = new QQShareContent();
		sinaShareContent = new SinaShareContent();
		String qqAppID =getResources().getString(R.string.w_qqAppID);
		String qqAppSecret = getResources().getString(R.string.w_qqAppSecret);
		// 参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, qqAppID, qqAppSecret);
		qqSsoHandler.addToSocialSDK();
		// 参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, qqAppID, qqAppSecret);
		qZoneSsoHandler.addToSocialSDK();
		String wxAppID = getResources().getString(R.string.w_wxAppID);
		String wxAppSecret = getResources().getString(R.string.w_wxAppSecret);
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(this, wxAppID, wxAppSecret);
		wxHandler.showCompressToast(false);
		wxHandler.addToSocialSDK();
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(this, wxAppID, wxAppSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.showCompressToast(false);
		wxCircleHandler.addToSocialSDK();

		listener = new SnsPostListener() {

			@Override
			public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
				// LogFile.logWrite("customId:" + arg2.mCustomID + ",EntityKey:"
				// + arg2.mEntityKey + ",SessionId:" + arg2.mSessionID +
				// ",extra=" + arg2.getExtra("access_token"));
				// LogFile.logWrite("SocializeEntity:"+arg2.toString() + arg2);
				if (arg1 == StatusCode.ST_CODE_SUCCESSED) {
					showToast(getResources().getString(R.string.share_ok));
					// 判断平台 请求完成任务接口

				} else if (arg1 == 40000) {
				} else {
					showToast(getResources().getString(R.string.share_fail));
				}
			}

			@Override
			public void onStart() {
				showToast(getResources().getString(R.string.shareing));
			}

		};

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// LogFile.logWrite(TAG + "-onDestroy");
		if (listener != null) {
			mController.unregisterListener(listener);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
		if (ssoHandler != null) {
			// LogFile.logWrite("onActivityResult" + data.toString());
			Bundle bundle = data.getExtras();
			if (bundle != null && !TextUtils.isEmpty(bundle.getString("uid"))) {
				// LogFile.logWrite("Uid:" + bundle.getString("uid") +
				// ",AccessToken:" + bundle.getString("access_token", "null"));
			}
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	public void getBitmapFromNet(final String url, final BitmapListener listener) {
		bitmapUtils.display(new ImageView(W_ShareAbstractActivity.this), url, new BitmapLoadCallBack<ImageView>() {

			@Override
			public void onLoadCompleted(ImageView container, String uri, Bitmap bitmap, BitmapDisplayConfig config, BitmapLoadFrom from) {
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 80, outputStream);
				listener.onResult(compressImageFromByte(outputStream.toByteArray()));
			}

			@Override
			public void onLoadFailed(ImageView container, String uri, Drawable drawable) {

				 Bitmap  bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallet_coupon_share_default_img);			
				 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
					bitmap.compress(CompressFormat.JPEG, 80, outputStream);
					listener.onResult(compressImageFromByte(outputStream.toByteArray()));
				
			}
		});
	}

	@SuppressWarnings("deprecation")
	private Bitmap compressImageFromByte(byte[] array) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;// 只读边,不读内容
		Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = 95f;//
		float ww = 95f;//
		int be = 1;
		if (w > h && w > ww) {
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置采样率

		newOpts.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
		newOpts.inPurgeable = true;// 同时设置才会有效
		newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

		bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, newOpts);
		return bitmap;
	}

	public interface BitmapListener {
		void onResult(Bitmap bitmap);
	}
}